package com.grayscale.core.rule;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import com.grayscale.core.adapt.GrayScaleRuleAdapt;
import com.grayscale.core.enums.GrayScaleTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * @author liuli
 * @date 2022/2/11
 * 参数格式  yyyy-MM-dd HH:mm:ss yyyy-MM-dd HH:mm:ss(24小时制)
 */
public class GrayScaleDateTimeIntervalRule implements GrayScaleRuleAdapt {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    private long sDateTime = 0;
    private long pStartDateTime = 0;
    private long pEndDateTime = 0;
    @Override
    public boolean process(String... parameter) {
        if (!check(parameter[0])){
            return false;
        }
        GrayScaleTypeEnum grayScaleTypeEnum = GrayScaleTypeEnum.getByType(parameter[1]);
        switch (grayScaleTypeEnum) {
            case BETWEEN_DATETIME:
                if (sDateTime > pStartDateTime && sDateTime < pEndDateTime){
                    return true;
                }
                break;
            case OUTSIDE_DATETIME:
                if (sDateTime < pStartDateTime || sDateTime > pEndDateTime){
                    return true;
                }
                break;
        }
        return false;
    }

    @Override
    public boolean check(String parameter) {
        try {
            sDateTime =  new DateTime(new Date()).getTime();
            pStartDateTime =  new DateTime(parameter.split(",")[0], DatePattern.NORM_DATETIME_FORMAT).getTime();
            pEndDateTime = new DateTime(parameter.split(",")[1], DatePattern.NORM_DATETIME_FORMAT).getTime();
        } catch (Exception e) {
            log.error("parameter format error:{} {}",parameter,e);
            return false;
        }
        return true;
    }
}
